/** 用户管理 */
import {Component, createRef} from "react";
import {Col, Form, Row, Table, DatePicker, Button, FormInstance, AutoComplete, Space, Typography, Modal, Input, Tag, Tooltip, message, Spin, Slider, Divider, Select} from "antd";

import {ColumnsType, TablePaginationConfig} from "antd/es/table";

import {URL, send} from '../../utils/http.util.tsx'
import {randomString, PageUtil, DEFAULT_PAGINATION, Handler, fmtMoney, nth} from '../../utils/util.tsx'

import LazyIcon from "../../components/Tools/Icon";

import {State, Data} from './types.tsx'

const {RangePicker} = DatePicker;
const {Link} = Typography;

// @ts-ignore
import './index.css'

import History from '../History'
import RechargeOrder from "./RechargeOrder";
import AvatarDetail from "../../components/Tools/Detail/Avatar";

class User extends Component<any, State> {
    historyRef = createRef<History>()
    rechargeOrderRef = createRef<RechargeOrder>()

    formRef = createRef<FormInstance>()
    tagAddFormRef = createRef<FormInstance>()

    columns: ColumnsType<Data> = [
        {
            title: '用户 ID',
            dataIndex: 'id',
            key: 'id'
        },
        {
            title: '用户名',
            dataIndex: 'nickName',
            key: 'nickName',
            render: (_, record) => <AvatarDetail headImg={record.headImg} nickName={record.nickName}/>
        },
        {
            title: '用户余额',
            dataIndex: 'currentBalance',
            key: 'currentBalance',
            render: (_, record) => {
                if (!record.currentBalance) {
                    return (
                        <>
                            <span>{fmtMoney(0.00)}</span>
                            <Divider type={"vertical"}/>
                            <Link onClick={() => this.showRechargeOrder(record.id, record.nickName)}>查看充值记录</Link>
                        </>
                    )
                }
                return (
                    <>
                        <span>{fmtMoney(record.currentBalance)}</span>
                        <Divider type={"vertical"}/>
                        <Link onClick={() => this.showRechargeOrder(record.id, record.nickName)}>查看充值记录</Link>
                    </>
                )
            }
        },
        {
            title: '标签',
            dataIndex: 'tags',
            key: 'tags',
            render: (_, record) => {
                const id: string = record.id

                if (!record.tags) {
                    return (
                        <Link onClick={() => this.setState({tagAddModalVisible: true, id: id, originTags: []})}>
                            <LazyIcon iconName={"Plus"}/>&nbsp;新增
                        </Link>
                    )
                }

                const tags: string[] = record.tags.split(',')
                const tagElements = tags.map(
                    (tag, index) => {
                        if (tag.length > 4) {
                            return (
                                <Tooltip title={tag} key={index}>
                                    <Tag key={index} closable={true} onClose={() => this.handleDeleteTag(record.id, tag, tags)}>`{tag.slice(0, 4)}...`</Tag>
                                </Tooltip>
                            )
                        } else {
                            return <Tag key={index} closable={true} onClose={() => this.handleDeleteTag(record.id, tag, tags)}>{tag}</Tag>
                        }
                    }
                );

                tagElements.push(
                    <>
                        <Divider type={"vertical"}/>
                        <Link onClick={() => this.setState({tagAddModalVisible: true, id: id, originTags: tags})} style={{position: "absolute", top: '17px'}}>
                            <LazyIcon iconName={"Plus"}/><span>新增</span>
                        </Link>
                    </>
                )
                return tagElements
            }
        },
        {
            title: '手机号',
            dataIndex: 'phoneNum',
            key: 'phoneNum',
            width: '100px'
        },
        {
            title: '注册时间',
            dataIndex: 'createdTime',
            key: 'createdTime',
            width: '180px'
        },
        {
            title: '操作',
            dataIndex: 'ops',
            key: 'ops',
            render: (_, record) => (
                <Space size="middle">
                    <Link onClick={() => this.showInstanceList(record.id, record.nickName)}>查看问卷</Link>
                </Space>
            )
        }
    ]

    state = {
        data: [], states: [],
        pagination: DEFAULT_PAGINATION,
        loading: true,
        visible: false,
        tagAddModalVisible: false, id: null, originTags: [],
        userNickname: '',

        optionsOfCreateBy: [], // CreateBy AutoComplete 组件的 options

        rechargeOrderModalVisible: false,
        rechargeOrderUserId: undefined, // 查看用户充值记录时, 用户的 ID
        rechargeOrderNickName: undefined, // 查看用户充值记录时, 用户的昵称

        tagOptions: []
    }

    componentDidMount() {
        this.handleFetch();

        send(URL.userTags).then(resp => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                this.setState({tagOptions: resp.data.data})
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    handleAddTag() {
        this.tagAddFormRef.current?.validateFields().then(values => {
            this.setState({loading: true}, () => {
                const newTag: string = values.input
                // @ts-ignore
                if (this.state.originTags.includes(newTag)) {
                    message.error('已存在该标签').then(nth)
                    return
                }
                const id = this.state.id
                send(URL.userTagUpdate, {id: id, tags: [...this.state.originTags, newTag].join(',')})
                    .then(resp => {
                        const httpCode = resp.data.httpCode
                        if (httpCode === 200) {
                            this.setState({tagAddModalVisible: false}, () => this.handleFetch())
                        } else Handler.ofHttpWarn(httpCode)
                    })
                    .catch(Handler.ofError)
            })
        }).catch(info => console.log('校验失败:', info))
    }

    handleDeleteTag = (id: string, tag: string, tags: string[]) => {
        send(URL.userTagUpdate, {id: id, tags: tags.filter(the => the !== tag).join(',')})
            .then(resp => {
                const httpCode = resp.data.httpCode
                if (httpCode === 200) {
                    this.handleFetch()
                } else Handler.ofHttpWarn(httpCode)
            })
            .catch(Handler.ofError)
    }

    handleFetch(qo: any = undefined, pagination: TablePaginationConfig | undefined = undefined) {
        this.setState({loading: true})

        if (qo) {
            if (qo.createTimeArr) {
                qo.createTimeStart = qo.createTimeArr[0].valueOf()
                qo.createTimeEnd = qo.createTimeArr[1].valueOf()
                delete qo.createTimeArr;
            }
            if (qo.currentBalanceArr) {
                qo.currentBalanceStart = qo.currentBalanceArr[0].valueOf()
                qo.currentBalanceEnd = qo.currentBalanceArr[1].valueOf()
                delete qo.currentBalanceArr;
            }
            if (qo.tagArr) {
                qo.tags = qo.tagArr.join(',')
                delete qo.tagArr
            }
        }

        send(URL.userQuery, {...qo, ...PageUtil.toDto(pagination)}).then(resp => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                const data = resp.data.data;
                this.setState(
                    {
                        data: data.records.map((item: { key: number, id: number }) => {
                                return {
                                    ...item,
                                    key: randomString()
                                }
                            }
                        ),
                        pagination: PageUtil.toPagination(data),
                        loading: false
                    }
                );
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    handleFetchNicknameLike(keyword: string) {
        send(URL.userNicknamesAutoComplete, {nickNameLike: keyword}).then((resp) => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                const data = resp.data.data;
                this.setState({optionsOfCreateBy: data})
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    /**
     * Description: 显示用户填写的问卷.
     * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-05-20 17:47:59
     */
    showInstanceList(userId: string, userNickname: string) {
        this.setState({visible: true, userNickname}, () => this.historyRef.current?.refresh(userId))
    }

    /**
     * Description: 显示用户的充值记录.
     * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-06-10 10:44:44
     */
    showRechargeOrder(userId: string, userNickname: string) {
        this.setState(
            {rechargeOrderModalVisible: true, rechargeOrderNickName: userNickname}, () => this.rechargeOrderRef.current?.refresh(userId)
        )
    }

    render() {
        const {data, pagination, loading, visible, tagAddModalVisible, userNickname} = this.state;
        const {rechargeOrderModalVisible, rechargeOrderNickName} = this.state
        const {tagOptions} = this.state

        return (
            <>
                <Form ref={this.formRef} onFinish={(qo) => this.handleFetch(qo)} className="queryForm" labelAlign={"right"}>
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item label="　用户名" name="nickNameLike">
                                <AutoComplete onSearch={(keyword) => this.handleFetchNicknameLike(keyword)} options={this.state.optionsOfCreateBy} placeholder="请输入关键字"/>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="注册时间" name="createTimeArr">
                                <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder={['开始时间', '结束时间']} style={{width: '100%'}}/>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="用户余额" name="currentBalanceArr">
                                <Slider range min={0} max={10000} tooltip={{formatter: fmtMoney}}/>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col span={16}>
                            <Form.Item label="　　标签" name="tagArr">
                                <Select mode="tags" style={{ width: '100%' }} options={tagOptions}/>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Space size={"middle"} style={{float: "right"}}>
                                <Button icon={<LazyIcon iconName="ClearOutlined"/>} htmlType="button" onClick={() => this.formRef.current?.resetFields()}>重置</Button>
                                <Button icon={<LazyIcon iconName="SearchOutlined"/>} type="primary" htmlType="submit">查询</Button>
                            </Space>
                        </Col>
                    </Row>
                </Form>
                <Table footer={() => `总共 ${this.state.pagination.total} 条数据`}
                       loading={loading} columns={this.columns} pagination={pagination} dataSource={data} onChange={(pagination) => this.handleFetch(undefined, pagination)}/>

                <Modal title={userNickname + "提交的问卷"} open={visible} centered keyboard width={"65%"} footer={null} onCancel={() => this.setState({visible: false})}>
                    <History ref={this.historyRef}></History>
                </Modal>

                <Modal title={"新增标签"} open={tagAddModalVisible} centered keyboard width={"25%"}
                       okText={"新增标签"} onOk={() => this.handleAddTag()} cancelText={"取消"} onCancel={() => this.setState({tagAddModalVisible: false})}>
                    <Spin spinning={loading}>
                        <Form ref={this.tagAddFormRef}>
                            <Form.Item name="input" rules={[{required: true, message: "新增标签不能为空"}]}>
                                <Input/>
                            </Form.Item>
                        </Form>
                    </Spin>
                </Modal>

                <Modal title={rechargeOrderNickName + "的充值记录"} centered keyboard width={"65%"} open={rechargeOrderModalVisible} footer={null}
                       onCancel={() => this.setState({rechargeOrderModalVisible: false})}>
                    <RechargeOrder ref={this.rechargeOrderRef} embedded={true}></RechargeOrder>
                </Modal>
            </>
        )
    }
}

// @ts-ignore
export default User;
